package com.heima.dao;

import com.heima.domian.User;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    /**
     * 添加
     * @param user
     */
    public   void  addUser(User user){
        try {
            Class.forName("com.mysql.jdbc.Driver");

           Connection conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/db10","root","itheima888");

            PreparedStatement preparedStatement = conn.prepareStatement("insert  into  t_user  values(null,?,?)");

            preparedStatement.setString(1,user.getName());
            preparedStatement.setInt(2,user.getAge());
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<User> findAll() {
        try {
            List<User>  users = new ArrayList<>();
            Class.forName("com.mysql.jdbc.Driver");

            Connection conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/db10","root","itheima888");

            PreparedStatement preparedStatement = conn.prepareStatement("select * from  t_user");

            ResultSet resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));
                users.add(user);
            }

            return   users;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

}
